#include "server_window.h"
#include "ui_server_window.h"
#include <iostream>
#include<string>
#include <unistd.h>
#include <sys/wait.h>
#include <fstream>
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
using namespace std;


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    path = "/home/nsatvik/Projects/DC_Project/DCP-v8.0/Server/";
    StartServer();
    initFileList();

}
void MainWindow::StartServer()
{
    string serverpath(path+"server");
    pid_t childpid = fork();
    if(childpid == 0)
    {
        execl(serverpath.c_str(),"Server",(char *)0); //no arguments for the server.
    }
}

MainWindow::~MainWindow()
{
    system("killall server");
    delete ui;
}
void MainWindow::ButtonRefreshHandler()
{
    initFileList();
}

void MainWindow::initFileList()
{
    QList<QString>  fileList;
    chdir(path.c_str());
    system("pwd");

    string command = "ls > file.list";
    cout<<command<<endl;
    system("cat file.list; stat file.list");
    system(command.c_str());
    ifstream infile;

    string file(path+"file.list");
    infile.open(file.c_str(),ios::in);
    ui->comboBoxFile->clear();
    ui->textBrowser->setText(QString::fromStdString(file));

    string filename;
    while(getline(infile, filename))
    {
        fileList.append(QString::fromStdString(filename));
    }

    infile.close();

    QStringList filestrlist(fileList);

    ui->comboBoxFile->insertItems(0, filestrlist);


}

void MainWindow::ButtonCompressHandler()
{

    string hufffile(path+"huff");

    QString qstr = ui->comboBoxFile->currentText();
    string input(path+qstr.toStdString());
    string output = input+".rir";

    ui->textBrowser->setText(QString::fromStdString(input + "\t" + output+"\t"+hufffile));

    pid_t childpid = fork();
    if(childpid == 0)
    {
        execl(hufffile.c_str(),"Compressor",input.c_str(),output.c_str(),0);
    }

    sleep(3);

    displayContentsOfFile(input);



}

void MainWindow::ButtonCreateFileHandler()
{


    string command("gedit ");
    command += path+ui->lineEditFileName->text().toStdString()+"&";
    if(system(command.c_str())==0)
    {
        cout<<"The system call was successfull"<<endl;


    }


}

void MainWindow::ButtonDecompressHandler()
{
    //string unhufffile(path+"unhuff");
    chdir(path.c_str());

    string input(ui->comboBoxFile->currentText().toStdString());//(path+ui->comboBoxFile->currentText().toStdString());
    cout<<input<<endl;
    string output = input.substr(0,input.length()-4);
    cout<<output<<endl;
    string command = "./unhuff "+input+" "+output;
    cout<<command<<endl;
    system(command.c_str());
//    // ui->textBrowser->setText(QString::fromStdString(input + "\t" + output+"\t"+unhufffile));
//    pid_t childpid = fork();
//    if(childpid == 0)
//    {
//        //execl(unhufffile.c_str(),"Decompressor",input.c_str(),output.c_str(),0);\\
//        execl("/home/nsatvik/c/odd","evenprog","12",(char *)0);
//    }
//    else
//    {
//        //sleep(3);
//        //displayContentsOfFile(path+output);

//    }
    displayContentsOfFile(path+output);
}

void MainWindow::ButtonDeleteFileHandler()
{
    string file(path+ui->lineEditFileName->text().toStdString());
    displayContentsOfFile(file);
    unlink(file.c_str());

}

void MainWindow::textChanged(QString str)
{



}
void MainWindow::displayContentsOfFile(string filenameStr)
{
    ifstream infile(filenameStr.c_str());
    //infile.open(filenameStr.c_str());
        if(!infile.is_open())
        {
            cout<<"HAHAH"<<endl;
            ui->textBrowser->append(QString::fromStdString("Error: "+filenameStr+" Not Found!"));
            ui->label_9->setText(QString::fromStdString("Error: "+filenameStr+" Not Found!"));
            cout<<"Error: "+filenameStr+" Not Found!"<<endl;
            return;
        }
    string fileContentsStr = "";

    QString fileContentsQStr;
    char ch;
    while(infile.get(ch))
    {
        fileContentsStr += ch;
    }

    fileContentsQStr.append(QString::fromStdString(fileContentsStr));

    ui->textBrowser->setText(fileContentsQStr);
    infile.close();

    displayFileSizes(filenameStr);
}

void MainWindow::displayFileSizes(string filenameStr)
{
    struct stat st;

    //For the actual file
    if(stat(filenameStr.c_str(), &st)==-1)
    {
        cout<<"Error: "<<filenameStr<<" not found!"<<endl;
        ui->label_9->setText(QString::fromStdString(filenameStr+": Details not found!"));
        ui->label_10->setText(QString::fromStdString(""));
        ui->label_11->setText(QString::fromStdString(""));
        return;
    }
    unsigned int actualSize = st.st_size;

    string fileSizeStr = "Actual File Size = " + integerToString(actualSize) + " bytes";
    QString fileSizeQStr = QString::fromStdString(fileSizeStr);
    ui->label_9->setText(fileSizeQStr);


    //For the Compressed File
    filenameStr += ".rir";
    if(lstat(filenameStr.c_str(), &st)==0)
    {
    int compressedSize = st.st_size;

    fileSizeStr = "Compressed File Size = " + integerToString(compressedSize) + " bytes";
    fileSizeQStr = QString::fromStdString(fileSizeStr);
    ui->label_10->setText(fileSizeQStr);

    //Compression Ratio
    fileSizeStr = "Compression Ratio = " + integerToString(compressedSize *100 / actualSize) + " %\n"
            +"Space Savings = "+ integerToString(actualSize-compressedSize)+" bytes";
    fileSizeQStr = QString::fromStdString(fileSizeStr);
    ui->label_11->setText(fileSizeQStr);
    }
}


string MainWindow::integerToString(int n)
{
    stringstream intstr;

    intstr << n;
    string str = "" + intstr.str();

    return str;
}
